package com.gitee.lw114514.tliasweb.filter;

import com.gitee.lw114514.tliasweb.utils.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

@Slf4j
@WebFilter(urlPatterns = "/**")  // 拦截所有请求  ,/* 则是拦截所有一级路径的请求
public class TokenFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //1.获取请求路径
        String requestURI = request.getRequestURI();
        log.info("拦截请求：{}", requestURI);

        //2.判断请求路径是否为登录路径
        if (requestURI.contains("/login")) {
            log.info("登录请求");
            filterChain.doFilter(request, response);
            return;
        }

        //3.判断token是否存在
        String token = request.getHeader("token");

        //4.判断token是否存在，如果token不存在，返回错误信息
        if (token == null || token.isEmpty()) {
            log.info("令牌为空，返回401");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);  //SC_UNAUTHORIZED = 401
            return;
        }
        log.info("令牌存在，开始解析");

        //5.如果token存在，继续执行，校验解析令牌，如果校验失败，返回错误信息
        try{
            JwtUtils.parseJwt(token);
        }catch (Exception e){
            log.info("令牌解析失败，返回401");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);  //SC_UNAUTHORIZED = 401
        }
        //6.如果校验成功，将用户信息保存，放行
        log.info("令牌解析成功，放行");
        filterChain.doFilter(request, response);

        //可以补充一些放行后要执行的逻辑

    }
}
